package com.shadt.core.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shadt.core.model.Json;
import com.shadt.core.service.UserService;
import com.shadt.core.util.ConfigUtil;
import com.shadt.core.util.SessionInfo;
import com.shadt.core.vo.UserVo;

/**
 * 用户控制器
 * 
 * @author SongR
 * 
 */
@Controller
@RequestMapping("/userAction")
public class UserController extends BaseController {
	@Autowired
	UserService userService;// 用户业务层实例

	/**
	 * 用户登录
	 * 
	 * @param userVo返回登录用户
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/login")
	public Json login(UserVo userVo, HttpSession session,
			HttpServletRequest request) {
		Json j = new Json();
		UserVo u = userService.login(userVo);
		if (u != null) {
			if (u.getIsAvailable().equals("1")) {
				j.setMsg("账号不可用！请联系管理员！");
				j.setSuccess(false);
			} else {
				j.setMsg("登陆成功！");
				j.setSuccess(true);
				// 登录用户信息存入Session
				SessionInfo sessionInfo = new SessionInfo();
				BeanUtils.copyProperties(u, sessionInfo);
				sessionInfo.setResourceList(userService.resourceList(u.getId()));
				sessionInfo.setMenuList(userService.getMenuList(sessionInfo));
				session.setAttribute(ConfigUtil.getSessionInfoName(),sessionInfo);
				// 用户信息也返回到客户端
				j.setObj(sessionInfo);
			}
		} else {
			j.setMsg("用户名或密码错误！");
		}
		return j;
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 *            用户对象
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/reg")
	public Json reg(UserVo user) {
		Json j = new Json();
		try {
			userService.reg(user);
			j.setSuccess(true);
			j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
			j.setObj(user);
		} catch (Exception e) {
			j.setMsg(e.getMessage());
		}
		return j;
	}

	/**
	 * 验证用户名是否存在
	 * 
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkName")
	public boolean checkName(String name, HttpSession session,
			HttpServletRequest request) {
		boolean isTrue = userService.checkUserName(name);
		return isTrue;
	}
	
	/**
	 * 验证密码是否正确
	 * 
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkPwd")
	public boolean checkPwd(String oldpwd,String id, HttpSession session,
			HttpServletRequest request) {
		boolean isTrue = userService.checkPwd(oldpwd,id);
		return isTrue;
	}

	/**
	 * 退出登录
	 * 
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/logout")
	public void logout(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (session != null) {
			session.removeAttribute(ConfigUtil.getSessionInfoName());
			session.invalidate();
		}
		response.sendRedirect(request.getContextPath() + "/login.jsp");
	}

	/**
	 * 跳转到用户管理页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/toUserManager")
	public String toUserManager(HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		return "page/usermanager";
	}

	/**
	 * 获取用户列表
	 * @param request
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUser")
	public String getUser(HttpServletRequest request, String name) {
		String names = request.getParameter("aoData");
		JSONArray jsonarray = JSONArray.parseArray(names);
		String sEcho = "", iDisplayStart = "", iDisplayLength = "", sSearch = "";
		for (int i = 0; i < jsonarray.size(); i++) {
			JSONObject obj = (JSONObject) jsonarray.get(i);
			if (obj.get("name").equals("sEcho"))
				sEcho = obj.get("value").toString();
			if (obj.get("name").equals("iDisplayStart")) // 开始显示行
				iDisplayStart = obj.get("value").toString();
			if (obj.get("name").equals("iDisplayLength")) // 每页显示的长度
				iDisplayLength = obj.get("value").toString();
			if (obj.get("name").equals("sSearch"))
				sSearch = obj.get("value").toString();
		}
		List<UserVo> userList = userService.getAllUsers(sSearch,
				Integer.parseInt(iDisplayStart),
				Integer.parseInt(iDisplayLength));
		String aaData = JSONArray.toJSONString(userList).toString();
		String json = "{\"sEcho\":" + sEcho + ",\"iTotalRecords\":"
				+ userService.getUsersCount(sSearch)
				+ ",\"iTotalDisplayRecords\":"
				+ userService.getUsersCount(sSearch) + ",\"aaData\":" + aaData
				+ "}";
		return json;
	}
	
	/**
	 * 根据用户编号删除用户
	 * @param request
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public String del(HttpServletRequest request, HttpSession session,String id){
		Json json = new Json();
		SessionInfo userSession=(SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		if(null!=userSession){
			if(id!=userSession.getId()&&!id.equals(userSession.getId())){
				boolean isTrue = userService.del(id);
				json.setSuccess(isTrue);
				if(isTrue){
					json.setMsg("删除成功！");
				}else{
					json.setMsg("删除失败！请联系管理员！");
				}
			}else{
				json.setMsg("不能删除当前登陆用户！");
			}
		}
		return JSONArray.toJSONString(json);
	}
	
	/**
	 * 根据用户编号修改用户密码
	 * @param request
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editPwd")
	public Json editPwd(HttpServletRequest request, HttpSession session,String id,UserVo vo){
		Json j = new Json();
		boolean isTrue = userService.editPwd(id,vo);
		j.setSuccess(isTrue);
		if(isTrue){
			j.setMsg("修改成功！");
		}else{
			j.setMsg("修改失败！请联系管理员！");
		}
		return j;
	}

	/**
	 * 根据用户编号获取用户信息
	 * @param request
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUserById")
	public Json getUserById(HttpServletRequest request, HttpSession session,String id){
		Json j = new Json();
		try {
			UserVo vo = userService.getUserById(id);
			j.setObj(vo);
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("系统异常！请联系管理员！");
			j.setSuccess(false);
		}
		return j;
	}
	
}
